import { BigInt } from "@graphprotocol/graph-ts"
import {
  Turnable,
  LuckReward,
  NewPlayer,
  WithDraw
} from "../generated/Turnable/Turnable"
import { User, Transaction } from "../generated/schema"

export function handleLuckReward(event: LuckReward): void {
  let transaction = Transaction.load(event.transaction.hash.toHex())
  if (transaction == null) {
    transaction = new Transaction(event.transaction.hash.toHex())
  }
  let user = User.load(event.transaction.from.toHex())
  transaction.name = user.name;
  if(event.params.random.equals(BigInt.fromI32(0))){
    transaction.type = BigInt.fromI32(0)
    transaction.num = event.params.reward
    user.reward = user.reward.plus(event.params.reward)
  }else if(event.params.random.lt(BigInt.fromI32(90))){
    transaction.type = BigInt.fromI32(1)
    transaction.num = event.params.reward
    user.reward = user.reward.plus(event.params.reward)
  }else if(event.params.random.lt(BigInt.fromI32(1800))){
    transaction.type = BigInt.fromI32(2)
    transaction.num = event.params.reward
    user.reward = user.reward.plus(event.params.reward)
  }else if(event.params.random.lt(BigInt.fromI32(60000))){
    transaction.type = BigInt.fromI32(3)
    transaction.num = event.params.gold
    if(event.params.gold.equals(BigInt.fromI32(1)) && event.params.reward.equals(BigInt.fromI32(1))){
      user.gold = BigInt.fromI32(0)
      user.reward = user.reward.plus(BigInt.fromI32(1))
    }else{
      user.gold = user.gold.plus(BigInt.fromI32(1))
    }
  }else{
    transaction.type = BigInt.fromI32(4)
    transaction.num = BigInt.fromI32(0)
  }
  transaction.timestamp = event.block.timestamp
  transaction.save()
  user.save()
}

export function handleWithDraw(event: WithDraw): void {
  let transaction = Transaction.load(event.transaction.hash.toHex())
  if (transaction == null) {
    transaction = new Transaction(event.transaction.hash.toHex())
  }
  let user = User.load(event.transaction.from.toHex())
  transaction.name = user.name;
  transaction.type = BigInt.fromI32(5)
  transaction.num = event.params.reward
  transaction.save();
}

export function handleNewPlayer(event: NewPlayer): void {
  let user = User.load(event.transaction.from.toHex())
  if (user == null) {
    user = new User(event.transaction.from.toHex())
    user.name = event.params.name;
    user.withdraw = BigInt.fromI32(0)
    user.reward = BigInt.fromI32(0)
    user.gold = BigInt.fromI32(0)
  }
  user.save()
}
